import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../api/DictApi.dart';
import '../../../utils/Settings.dart';
import '../../../utils/StoreData.dart';
import '../../../utils/Utils.dart';
import '../../form/LFormLogic.dart';
import '../../get/MyController.dart';
import 'LFormCascaderState.dart';

class LFormCascaderLogic extends MyController{

  final state = LFormCascaderState();
  late String title;
  void init({required Map formItem,required Map formData,String? betweenSign,required String formTag,required String formType}){
    state.formItem = formItem;
    state.formData = formData??{};
    state.defaultText = "";
    state.betweenSign = betweenSign??"";
    state.resultOptions = [];
    state.dictOptions = [];
    state.intslectedIndex = -1;
    state.parentItemList = [];//记录进入当前选择页面所有父级菜单信息
    state.pageCount = 1;//一共多少页
    state.pageOptions = {};//每页存放的数据，
    state.selectedOption = {};//选中的
    state.currentIndex = 0;
    state.pageController = PageController(initialPage: state.currentIndex,keepPage: true);
    state.formTag = formTag;
    state.formType = formType;

    initDic();
  }

  void initDic()async{
    if(state.formItem["dictCode"]==null){
      return;
    }
    //初始化数据字典信息
    await DictApi.initDict(state.formItem["dictCode"], "", []);
    state.resultOptions = StoreData.dictInfo[state.formItem["dictCode"]];
    //将所有数据默认放到第一页
    state.pageOptions['page0']=state.resultOptions;
    state.dictOptions = state.resultOptions;
    initPageCount(state.dictOptions);
  }

  //看一共多少页
  initPageCount(options){
    for(var item in options){
      if(!Utils.isEmpty(state.formData['${state.formItem["field"]}${state.betweenSign}'])){
        //设置默认值
        if(item["value"]==state.formData['${state.formItem["field"]}${state.betweenSign}']){
          state.formData['${state.formItem["field"]}${state.betweenSign}'] = item["value"];
          state.defaultText = item["title"];
        }
      }

      if(item["children"]!=null){
        state.pageCount++;
        initPageCount(item["children"]);
      }
    }
    update();
  }

  Future<dynamic> showCustomModalBottomSheet(context, List options) async {
    //每次都是从第一页开始，
    state.currentIndex = 0;
    return showModalBottomSheet<dynamic>(
      backgroundColor: Colors.transparent,
      isScrollControlled: true,
      context: context,
      builder: (BuildContext context) {
        return Container(
          clipBehavior: Clip.antiAlias,
          decoration: const BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(20.0),
              topRight: Radius.circular(20.0),
            ),
          ),
          height: MediaQuery.of(context).size.height / 2.0,
          child: Column(children: [
            SizedBox(
              height: 50,
              child: Stack(
                textDirection: TextDirection.rtl,
                children: [
                  Align(
                    alignment: Alignment.topLeft,
                    child: IconButton(
                        icon: const Icon(Icons.arrow_back_ios),
                        onPressed: () async{
                          if(state.currentIndex>0){
                            state.currentIndex--;
                            state.pageCount--;
                            options = state.pageOptions['page${state.currentIndex}'];
                            state.pageController.jumpToPage(state.currentIndex);
                          }else{
                            //清空选择的内容
                            state.formData['${state.formItem["field"]}${state.betweenSign}'] = null;
                            state.defaultText = "";
                            if(state.formType==Settings.formType["表单"]){
                              Get.find<LFormLogic>(tag: state.formTag).onChange({'field':'${state.formItem["field"]}${state.betweenSign}','val':null});
                            }
                          }
                          update();
                        }),
                  ),
                  Center(
                    child: Text(
                      '${state.formItem["label"]}选择',
                      style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16.0),
                    ),
                  ),
                  IconButton(
                      icon: const Icon(Icons.close),
                      onPressed: () {Navigator.of(context).pop();}),
                ],
              ),
            ),
            const Divider(height: 1.0),

            Expanded(
                child:PageView.builder(
                  physics: const NeverScrollableScrollPhysics(),
                  controller: state.pageController,
                  scrollDirection: Axis.horizontal,
                  itemCount: state.pageCount,
                  itemBuilder: (context, pageIndex) {
                    return ListView.builder(
                      itemCount: options.length,
                      itemBuilder: (BuildContext context, int index) {

                        return  ListTile(
                            title: Text(options[index]["title"]),
                            trailing: options[index]["children"]!=null?const Icon(Icons.keyboard_arrow_right):null,
                            onTap: () async{
                              if(state.selectedOption["value"] != options[index]["value"]){
                                state.selectedOption = options[index];
                                if(state.formType==Settings.formType["表单"]){
                                  Get.find<LFormLogic>(tag: state.formTag).onChange({'field':'${state.formItem["field"]}${state.betweenSign}','val':options[index]["value"]});
                                }
                              }
                              state.formData['${state.formItem["field"]}${state.betweenSign}'] = options[index]["value"];
                              state.defaultText = options[index]["title"];
                              if(options[index]["children"]!=null){
                                if(state.currentIndex<state.pageCount){
                                  options = options[index]["children"];
                                  state.currentIndex++;
                                  state.pageCount++;
                                  state.pageOptions['page${state.currentIndex}'] = options;
                                  state.pageController.jumpToPage(state.currentIndex);
                                }
                              }
                              update();
                            });
                      },
                    );
                  },
                )
            ),
          ]),
        );
      },
    );
  }
}